/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.util;

import java.io.UnsupportedEncodingException;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.DBAdapter;
import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.ui.EventMultiPaneActivity;
import edu.bsu.android.gtv.apps.bconnected.ui.HomeActivity;
import edu.bsu.android.gtv.apps.bconnected.ui.LoginActivity;
import edu.bsu.android.gtv.apps.bconnected.util.AboutHelper;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

/**
 * A class that handles some common activity-related functionality in the app, such as setting up
 * the action bar. 
 */
public class ActivityHelper {
    protected Activity mActivity;

    /**
     * Factory method for creating {@link ActivityHelper} objects for a given activity. Depending
     * on which device the app is running, either a basic helper or Honeycomb-specific helper will
     * be returned.
     */
    public static ActivityHelper createInstance(Activity activity) {
        return new ActivityHelper(activity);
    }

    protected ActivityHelper(Activity activity) {
        mActivity = activity;
    }

    public void fireTrackerEvent(String label) {
        AnalyticsUtils.getInstance(mActivity).trackEvent("Action bar", "Click", label, 0);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        mActivity.getMenuInflater().inflate(R.menu.default_menu_items, menu);
        
        // If the student has logged in and the credentials are still valid, hide the login menu option, else, show the logout option
        if (LoginHelper.hasLoggedIn(mActivity)) {
            menu.findItem(R.id.menu_login).setVisible(false);
            menu.findItem(R.id.menu_logout).setVisible(true);
        } else {
            menu.findItem(R.id.menu_login).setVisible(true);
            menu.findItem(R.id.menu_logout).setVisible(false);
        }
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case android.R.id.home:
	            // Handle the HOME / UP affordance. Since the app is only two levels deep hierarchically, UP always just goes home.
	            goHome();
	            return true;
            case R.id.menu_logout:
            	goLogout();
                return true;
	        case R.id.menu_login:
	        	goLogin();
	            return true;
            case R.id.menu_about:
                AboutHelper.showAbout(mActivity);
            	return true;
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return false;
    }

    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goHome();
            return true;
        }
        return false;
    }

    public void setupActionBar(boolean home) {  
        ActionBar bar = mActivity.getActionBar();
        bar.setTitle(mActivity.getString(R.string.app_name));

        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_schedule)
        		.setText(mActivity.getString(R.string.btn_schedule))
        		.setTabListener(new TabListener("schedule")), false);
        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_student_orgs)
        		.setText(mActivity.getString(R.string.btn_student_orgs))
        		.setTabListener(new TabListener("orgs")), false);
        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_home)
        		.setText(mActivity.getString(R.string.btn_home))
        		.setTabListener(new TabListener("housing")), false);
        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_connections)
        		.setText(mActivity.getString(R.string.btn_connections))
        		.setTabListener(new TabListener("connections")), false);
        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_about_me)
        		.setText(mActivity.getString(R.string.btn_about_me))
        		.setTabListener(new TabListener("aboutme")), false);
        bar.addTab(bar.newTab()
        		.setIcon(R.drawable.home_btn_events)
        		.setText(mActivity.getString(R.string.btn_events))
        		.setTabListener(new TabListener("events")), false);
        
        if (home) {
            bar.setDisplayUseLogoEnabled(true);
        } else { 
        	bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO); 
            bar.setDisplayUseLogoEnabled(false);
        }
        
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayShowHomeEnabled(true);
        bar.setDisplayShowTitleEnabled(false);   
    }
	
	private class TabListener implements ActionBar.TabListener {
		String mTab = null;
		
		TabListener(String tab) {
			mTab = tab;
		}
		
		public void onTabSelected(ActionBar.Tab tab, FragmentTransaction unused) {
            fireTrackerEvent(mTab.toString());
            Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, LoginActivity.class);
            
			if (mTab.equals("schedule")) {
                intent.putExtra(Constants.EXTRA_DESTINATION_FRAGMENT, Integer.toString(Constants.DESTINATION_SCHEDULE));
			} else if (mTab.equals("orgs")) {
                intent.putExtra(Constants.EXTRA_DESTINATION_FRAGMENT, Integer.toString(Constants.DESTINATION_STUDENT_ORGS));               
			} else if (mTab.equals("housing")) {
                intent.putExtra(Constants.EXTRA_DESTINATION_FRAGMENT, Integer.toString(Constants.DESTINATION_MY_HOME));
			} else if (mTab.equals("connections")) {
               	intent.putExtra(Constants.EXTRA_DESTINATION_FRAGMENT, Integer.toString(Constants.DESTINATION_MY_CONNECTIONS));
			} else if (mTab.equals("aboutme")) {
                intent.putExtra(Constants.EXTRA_DESTINATION_FRAGMENT, Integer.toString(Constants.DESTINATION_ABOUT_ME));
			} else if (mTab.equals("events")) {
				intent = new Intent(Intent.ACTION_VIEW, null, mActivity, EventMultiPaneActivity.class);
			} 
            
            mActivity.startActivity(intent);
		}

		public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction unused) {
			// TODO: Implement
		}

		public void onTabReselected(ActionBar.Tab tab, FragmentTransaction xaction) {
			// TODO: Implement
		}
	}

    /**
     * Invoke "home" action, returning to {@link HomeActivity}.
     */
    public void goHome() {
        if (mActivity instanceof HomeActivity) { 
            return;
        }

        final Intent intent = new Intent(mActivity, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mActivity.startActivity(intent);
        mActivity.overridePendingTransition(R.anim.home_enter, R.anim.home_exit);
    }

    /**
     * Invoke "logout" action which will reset the local security table and shared preferences
     */
    public void goLogout() {
        DBAdapter db = new DBAdapter(mActivity);
        db.open();
	    
	    // Retrieve the most recent activity for the user
        final Cursor data = db.getSecurityMostRecent();
        
        mActivity.startManagingCursor(data);  

        // Update the shared preferences, delete the local SQLite credentials and initialize the logout service call to the SQL Server back-end
        if (data.getCount() > 0) {  
        	LoginHelper.setLogin(mActivity, false);
        	LoginHelper.setDemoAccount(mActivity, false);
        	
	    	db.deleteSecurityAll(); 

            Runnable load = new Runnable(){
                public void run() {             
                	String guid = data.getString(data.getColumnIndexOrThrow(DBAdapter.KEY_UNIQUE_ID));
                	String bsuID = data.getString(data.getColumnIndexOrThrow(DBAdapter.KEY_BSUID));
                	
        	    	// Call the .NET XML handler to delete the login credentials on SQL Server
        	    	// NOTE: Pass the encrypted login guid and bsu id
                	try {
						PersonData.initializeLogout(bsuID, guid, mActivity);
					} catch (UnsupportedEncodingException ex) {
						Log.e("ActivityHelper", ex.getMessage());
					} 
                }
            };
            
            Thread thread =  new Thread(null, load, "logout");
            thread.start();
        } 

        mActivity.stopManagingCursor(data);
        //data.close();
        db.close();
        
        // Broadcast the intent to the receivers throughout the application.  This will ensure that they prompt the user to log into
        // the application before accessing any of the secure content.
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(Constants.ACTION_LOGOUT);
        mActivity.sendBroadcast(broadcastIntent);
        
        final Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
        
        mActivity.startActivity(intent); 
        mActivity.finish(); 
    }
    
    /**
     * Invoke "login" action and pass control to the {@link LoginActivity}
     */
    public void goLogin() { 
        final Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, LoginActivity.class);
        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGIN));
        
        mActivity.startActivity(intent);
    }
}
